//
//  BGAddInfoPageController.m
//  bigMall
//
//  Created by LTOVE on 16/8/29.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGAddInfoPageController.h"
#import "BGDateResult.h"
#import "BGAddInfoTableViewCell.h"
//#import "BGAddInfoBasicModel.h"
#import "BGAddinfopickViewModel.h"
#import "BGGoodAttrsModel.h"
#import "BGCategoryAttrResultModel.h"
#import "BGCategoryAttrModel.h"
#import "BGId_ValueModel.h"
#import "MJExtension.h"

#import "LTOVEDynamicCreakButton.h"
#import "BGMyTenderTableViewController.h"
#import "BGAddInviteTwoModel.h"

#import "MBProgressHUD+MJ.h"
#import "MBProgressHUD.h"

@interface BGAddInfoPageController ()<BGAddInfoTableViewCellDelegate,dynamicButtonDelegate>{
    
    NSMutableArray *_dateArray;
//    UIGestureRecognizer *_gest;
    NSString *_invite_ids;
    BOOL isDate;
//    LTOVEDynamicCreakButton *_view;
}

@property (nonatomic,strong)BGAddInfoParamModel *paramModel;
@property (nonatomic,weak)LTOVEDynamicCreakButton *views;

@end

@implementation BGAddInfoPageController

- (BGAddInfoParamModel *)paramModel
{
    if (!_paramModel) {
        _paramModel = [[BGAddInfoParamModel alloc]init];
        _paramModel.inviteId = @"11";
//        _paramModel.attrValue = [NSMutableArray array];
    }
    return _paramModel;
}

- (void)setStatus:(BOOL)status
{
    _status = status;
    isDate = self.status;
    self.views.hidden = !self.status;
}
//- (instancetype)init
//{
//    if (self = [super init]) {
//        
//    }
//    return self;
//}
#pragma mark - 退出按钮
/**
 *  退出发布
 */
- (void)loginOut
{
//    [self.navigationController popToRootViewControllerAnimated:YES];
//    NSInteger sa = self.navigationController.vie
    
    NSInteger indexaa=[[self.navigationController viewControllers]indexOfObject:self];
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:indexaa-2]animated:YES];
//    [self.navigationController popToViewController:<#(nonnull UIViewController *)#> animated:<#(BOOL)#>]
}

//- (void)setParamModel:(BGAddInfoParamModel *)paramModel
//{
//
//}
- (void)dynamicButtonClick:(UIButton *)btn
{
    [BGDateResult addInviteTwoWithParam:self.paramModel.keyValues success:^(NSObject *result) {
        BGAddInviteTwoModel *model = (BGAddInviteTwoModel *)result;
        GWLog(@"%@",model.msg);
        
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:model.msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            if ([model.status isEqualToString:@"1"]) {
                BGMyTenderTableViewController *vc = [[BGMyTenderTableViewController alloc]init];
                vc.title = @"我的招标";
                UIBarButtonItem *bacItem = [[UIBarButtonItem alloc]init];
                bacItem.title = @"";
                self.navigationItem.backBarButtonItem = bacItem;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
        [alertVc addAction:sure];
        [self presentViewController:alertVc animated:YES completion:^{
            
            
        }];
        
        
    } failure:^(NSError *error) {
        
        
    }];
}
- (void)setInvite_id:(NSString *)invite_id
{
    _invite_id = invite_id;
//    if (!_paramModel) {
//        _paramModel = [[BGAddInfoParamModel alloc]init];
//    }
    BGAddInfoParamModel *pModel = [[BGAddInfoParamModel alloc]init];
    pModel.inviteId = invite_id;
    self.paramModel = pModel;
}
- (void)cellValueChangedStr:(BGAddInfoBasicModel *)model
{
//    BGAddInfoParamModel *tempModel = self.paramModel;
    if (!self.paramModel.attrValue) {
        _paramModel.attrValue = [NSMutableArray array];
//        for (int i = 0; i < _dateArray.count; i++) {
//            [self.paramModel.attrValue addObject:@""];
//        }
    }
//    BGAddInfoParamValueModel *itemModel = [[BGAddInfoParamValueModel alloc]init];
//    itemModel.attrId = model.idStr;
//    GWLog(@"%@",model.idStr);
    
    if ([model isKindOfClass:[BGAddInfoDoubleSelectedViewModel class]]) {
//        itemModel.value = model.changeDoubleArrayValue;
//        BOOL isHave = NO;
        NSLog(@"%@",self.paramModel.keyValues);
//        for (BGAddInfoParamValueModel *tempModel in self.paramModel.attrValue) {
//            if ([tempModel.attrId isEqualToString:model.idStr]) {
//                [self.paramModel.attrValue removeObject:tempModel];
//            }
//        }
        NSInteger count = self.paramModel.attrValue.count;
        for (int i = 0; i < count; i++) {
            BGAddInfoParamValueModel *tempModel = self.paramModel.attrValue[i];
            if ([tempModel.attrId isEqualToString:model.idStr]) {
                [self.paramModel.attrValue removeObjectAtIndex:i];
                i-=1;
                count -=1;
            }
        }
        for (NSString *strs in model.changeDoubleArrayValue) {
            BGAddInfoParamValueModel *itemModel = [[BGAddInfoParamValueModel alloc]init];
            itemModel.attrId = model.idStr;
            itemModel.value = strs;
            [self.paramModel.attrValue addObject:itemModel];
        }
        
        
        
    }else{
        BGAddInfoParamValueModel *itemModel = [[BGAddInfoParamValueModel alloc]init];
        itemModel.attrId = model.idStr;
         itemModel.value = model.changedStr;
        BOOL isHave = NO;
        for (BGAddInfoParamValueModel *tempModel in self.paramModel.attrValue) {
            if ([tempModel.attrId isEqualToString:model.idStr]) {
                isHave = YES;
            }
        }
        if (isHave) {
            NSInteger count = self.paramModel.attrValue.count;
            for (int i = 0; i < count; i++) {
                BGAddInfoParamValueModel *tempModel = self.paramModel.attrValue[i];
                if ([tempModel.attrId isEqualToString:model.idStr]) {
                    [self.paramModel.attrValue replaceObjectAtIndex:i withObject:itemModel];
                    i-=1;
                    count -=1;
                }
            }
//            [_paramModel.attrValue replaceObjectAtIndex:model.index withObject:itemModel];
        }else{
            [_paramModel.attrValue addObject:itemModel];
        }
        
        
//        itemModel.value = model.changedStr;
    }
//    [_paramModel.attrValue replaceObjectAtIndex:model.index withObject:itemModel];
    
    [_dateArray replaceObjectAtIndex:model.index withObject:model];
    [self.tableView reloadData];
   
    
    GWLog(@"<<<<<<<<<<<<<<<%@",_paramModel.keyValues);
}



- (instancetype)init
{
    if (self = [super init]) {
        //加载附加信息参数
//        BGAddinfopickViewModel *model = [BGAddinfopickViewModel new];
//        model.title = @"ddd";
//        model.dateArray = @[@[@"ss",@"ss"]];
//        BGAddinfoTextFildViewModel *textFildModel = [BGAddinfoTextFildViewModel new];
//        textFildModel.title = @"你好";
//        BGAddInfoDoubleSelectedViewModel *doubleModel = [BGAddInfoDoubleSelectedViewModel new];
//        doubleModel.title = @"我不好";
//        doubleModel.doubleSelectDateArray = @[@"123",@"321"];
//        doubleModel.heigh = 100;
//        _dateArray = [NSMutableArray arrayWithObjects:model,textFildModel,doubleModel, nil];
//        [self.tableView reloadData];
        
        //加载数据
        UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"退出" style:UIBarButtonItemStylePlain target:self action:@selector(loginOut)];
        self.navigationItem.rightBarButtonItem = right;
        
        
        
    }
    return self;
}

- (void)setCatId:(NSString *)catId
{
    _catId = catId;
    [self loadAttrData];
}
/**
 *  加载属性列表数据
 */
- (void)loadAttrData
{
    [MBProgressHUD showMessage:@"加载中..."];
    [BGDateResult categoryAttrWithCatId:self.catId success:^(NSObject *result) {
        [MBProgressHUD hideHUD];
        BGCategoryAttrResultModel *model = (BGCategoryAttrResultModel *)result;
        NSArray *array = model.res;
        if (!_dateArray) {
            _dateArray = [NSMutableArray array];
        }
        NSMutableArray *oneArray = [NSMutableArray array];
        NSMutableArray *twoArray = [NSMutableArray array];
        NSMutableArray *threeArray = [NSMutableArray array];
        for (BGCategoryAttrModel *itemModel in array) {
            if ([itemModel.attr_type isEqualToString:@"1"] || [itemModel.attr_type isEqualToString:@"2"]) {
                //文本
                BGAddinfoTextFildViewModel *textFildModel = [BGAddinfoTextFildViewModel new];
                textFildModel.title = [NSString stringWithFormat:@"%@ :",itemModel.name];
                textFildModel.idStr = itemModel.idStr;
                textFildModel.textFildStr = [self oneValueStrWithAttId:itemModel.idStr];
                [oneArray addObject:textFildModel];
            }else if ([itemModel.attr_type isEqualToString:@"3"]  || [itemModel.attr_type isEqualToString:@"5"]){
                //下拉
                BGAddinfopickViewModel *model = [BGAddinfopickViewModel new];
//                model.title = [NSString stringWithFormat:@"%@ :",itemModel.name];
                 model.title = [NSString stringWithFormat:@"%@ :%@",itemModel.name,[self oneValueStrWithAttId:itemModel.idStr]];
                NSArray *array = itemModel.attr_values;
                NSMutableArray *vauleNameArray = [NSMutableArray array];
                for (BGId_ValueModel *valueModel in array) {
                    [vauleNameArray addObject:valueModel.value];
                    
                }
//                model.dateArray = @[@[@"ss",@"ss"]];
                model.idStr = itemModel.idStr;
                model.dateArray = @[vauleNameArray];
                [twoArray addObject:model];
            }else if ([itemModel.attr_type isEqualToString:@"4"]){
                //多选
                BGAddInfoDoubleSelectedViewModel *doubleModel = [BGAddInfoDoubleSelectedViewModel new];
                doubleModel.title = [NSString stringWithFormat:@"%@ :",itemModel.name];
                NSMutableArray *valueArray = [NSMutableArray array];
                NSMutableArray *selectedArray = [NSMutableArray array];
                for (BGId_ValueModel *valueModel in itemModel.attr_values) {
                    [valueArray addObject:valueModel.value];
                }
                for (int i = 0; i < itemModel.attr_values.count; i++) {
//                    BOOL is = NO;
//                    [selectedArray addObject:@"0"];
                    selectedArray = [self selectIndexArrayWithAttrArray:itemModel.attr_values andAttrId:itemModel.idStr];
                }
                doubleModel.doubleSelectDateArray = valueArray;
                doubleModel.doubBtnSelected = selectedArray;
//                GWLog(@"--------%@",selectedArray);
                doubleModel.heigh = 30 + 20 * itemModel.attr_values.count;
                doubleModel.idStr = itemModel.idStr;
                [threeArray addObject:doubleModel];
            }else{
                
            }
            
        }
        [_dateArray addObjectsFromArray:oneArray];
        [_dateArray addObjectsFromArray:twoArray];
        [_dateArray addObjectsFromArray:threeArray];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideHUD];
    }];
}
- (void)setAttrArray:(NSArray *)attrArray
{
    _attrArray = attrArray;
    isDate = self.isDates;
    GWLog(@"%@",attrArray);
}
/**
 *  查找对应的value值
 *
 *  @param attId attId description
 *
 *  @return return value description
 */
- (NSString *)oneValueStrWithAttId:(NSString *)attId
{
    NSString *str = [NSString string];
    for (BGGoodAttrsModel *model in self.attrArray) {
        GWLog(@"%@---%@",model.attrId,attId);
        if ([model.attrId isEqualToString:attId]) {
            str = model.value;
            GWLog(@"%@",str);
        }
    }
    return str;
}
/**
 *  选中数组
 *
 *  @param attrArray attrArray description
 *  @param attrId    attrId description
 *
 *  @return return value description
 */
- (NSMutableArray *)selectIndexArrayWithAttrArray:(NSArray *)attrArray andAttrId:(NSString *)attrId
{
    NSMutableArray *selectedArray = [NSMutableArray array];
    
    for (BGId_ValueModel *model in attrArray) {
        [selectedArray addObject:@"0"];
        for (BGGoodAttrsModel *itemModel in self.attrArray) {
            if ([model.value isEqualToString:itemModel.value]) {
//                [selectedArray addObject:@"1"];
                [selectedArray replaceObjectAtIndex:selectedArray.count - 1 withObject:@"1"];
            }
        }
    }
    
    return selectedArray;
}


- (void)viewWillAppear:(BOOL)animated
{
    
    [self addDynamicBtn];
    self.views.hidden = !self.status;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.views removeFromSuperview];
}
- (void)addDynamicBtn
{
    NSDictionary *dic = @{
                          NSFontAttributeName:Font34,
                          NSForegroundColorAttributeName:[UIColor whiteColor]
                          };
    //    NSLog(@"%@",_btnArray);
    CGFloat x = BGButtonCellHeigh;
    CGFloat heigh = screenH - x;
    NSArray *_btnArray = @[@"立即发布"];
    LTOVEDynamicCreakButton *view = [LTOVEDynamicCreakButton buttonViewWithFrame:CGRectMake(0, heigh, screenW, BGButtonCellHeigh) titleDataArray:_btnArray andCol:(int)_btnArray.count andEdgInset:UIEdgeInsetsMake(10,BGMaginLeft , 10, BGMaginLeft) andMaginX:10 andMaginY:0 andBtnHeigh:BGMessageBtn andBtnNorColor:read_ andBtnHeighColor:read_ andRadius:7 andFont:dic];
    //    LTOVEDynamicCreakButton *view = [LTOVEDynamicCreakButton buttonViewWithFrame:CGRectMake(0,heigh, screenW, BGButtonCellHeigh) titleDataArray:self.btnArray andEdgInset:UIEdgeInsetsMake(10, BGMaginLeft, 10, BGMaginLeft) andMaginX:0 andMaginY:0 andBtnHeigh:BGMessageBtn andBtnNorColor:read_ andBtnHeighColor:read_ andRadius:7 andFont:dic];
    //    view.delegate = self;
    //    view.y = 300;
    self.views = view;
//    self.views.hidden = YES;
    view.delegate = self;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, x, 0);
    [BGKeyWindow addSubview:view];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    //键盘出现的通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShowNotif) name:UIKeyboardDidShowNotification object:nil];
//    //键盘消失的通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDismissMode) name:UIKeyboardDidHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShowNotif) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDissmissNotify) name:UIKeyboardDidHideNotification object:nil];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
/**
 *  关闭键盘
 */
- (void)closeKeyBoard
{
        [self.tableView endEditing:YES];
}

/**
 *  键盘出现的通知
 */
- (void)keyBoardShowNotif
{
//    _gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeKeyBoard)];
//    [self.tableView addGestureRecognizer:_gest];
    
//    _gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeKeyBoard)];
//    [self.tableView addGestureRecognizer:_gest];
}
/**
 *  键盘消失的通知
 */
- (void)keyBoardDissmissNotify
{
    //    [self.tableView removeGestureRecognizer:_gest];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return _dateArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BGAddInfoTableViewCell *cell = [BGAddInfoTableViewCell cellWithTableview:tableView];
    BGAddInfoBasicModel *model = _dateArray[indexPath.row];
    cell.model =model;
    cell.model.index = indexPath.row;
    cell.delegate = self;
    cell.userInteractionEnabled = self.status;
    // Configure the cell...
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BGAddInfoBasicModel *model = _dateArray[indexPath.row];
    if (model.option) {
        model.option();
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BGAddInfoBasicModel *model = _dateArray[indexPath.row];
    if ([model isKindOfClass:[BGAddInfoDoubleSelectedViewModel class]]) {
        BGAddInfoDoubleSelectedViewModel *itemModel = (BGAddInfoDoubleSelectedViewModel *)model;
        return itemModel.heigh;
    }
    return 44;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
